﻿import 'package:get/get.dart';
import 'package:getx_scaffold/common/utils/toast_util.dart';
import 'package:azring/core/repository/default_api.dart';
import 'menstrual_cycle_notification_state.dart';

/// 生理期提醒控制器
class MenstrualCycleNotificationLogic extends GetxController {
  final MenstrualCycleNotificationState state =
      MenstrualCycleNotificationState();

  @override
  void onInit() {
    super.onInit();
    loadReminderSettings();
  }

  /// 加载提醒设置
  Future<void> loadReminderSettings() async {
    try {
      final result =
          await DefaultApi().queryReminderInfoGet<Map<String, dynamic>>();

      if (result != null &&
          result['code'] == 200 &&
          result['data'] != null) {
        final data = result['data'];

        // 解析开关状态 (假设后端返回 "0" 或 "1" 字符串)
        state.periodReminderEnabled.value =
            data['isMenstrualPeriod'] == '1' || data['isMenstrualPeriod'] == 1;
        state.ovulationReminderEnabled.value =
            data['isOvulationPeriod'] == '1' || data['isOvulationPeriod'] == 1;
        state.ovulationDayReminderEnabled.value =
            data['isPeriodDays'] == '1' || data['isPeriodDays'] == 1;
        state.ovulationEndReminderEnabled.value =
            data['isOvulationPeriodEnd'] == '1' ||
                data['isOvulationPeriodEnd'] == 1;

        // 设置提醒时间
        if (data['reminderTime'] != null) {
          state.reminderTime.value = data['reminderTime'];
        }

        // 更新全部启用状态
        updateAllEnabledStatus();
      } else {
        // 如果没有数据，使用默认值
        initializeDefaultSettings();
      }
    } catch (e) {
      print('加载提醒设置失败: $e');
      initializeDefaultSettings();
    }
  }

  /// 初始化默认设置
  void initializeDefaultSettings() {
    state.allEnabled.value = false;
    state.periodReminderEnabled.value = false;
    state.ovulationReminderEnabled.value = false;
    state.ovulationDayReminderEnabled.value = false;
    state.ovulationEndReminderEnabled.value = false;
    state.reminderTime.value = '10:00';
  }

  /// 切换全部启用状态
  void toggleAllEnabled(bool value) {
    state.allEnabled.value = value;
    
    // 同时更新所有单项开关
    state.periodReminderEnabled.value = value;
    state.ovulationReminderEnabled.value = value;
    state.ovulationDayReminderEnabled.value = value;
    state.ovulationEndReminderEnabled.value = value;
  }

  /// 切换单个通知项状态
  void toggleNotificationItem(RxBool itemEnabled, bool value) {
    itemEnabled.value = value;
    
    // 检查是否所有项都已启用或禁用
    updateAllEnabledStatus();
  }

  /// 更新全部启用状态
  void updateAllEnabledStatus() {
    final allItemsEnabled = state.periodReminderEnabled.value &&
                           state.ovulationReminderEnabled.value &&
                           state.ovulationDayReminderEnabled.value &&
                           state.ovulationEndReminderEnabled.value;
    
    final anyItemEnabled = state.periodReminderEnabled.value ||
                          state.ovulationReminderEnabled.value ||
                          state.ovulationDayReminderEnabled.value ||
                          state.ovulationEndReminderEnabled.value;
    
    // 如果所有项都启用，则全部启用为true
    // 如果没有任何项启用，则全部启用为false
    // 如果部分启用，保持当前状态
    if (allItemsEnabled) {
      state.allEnabled.value = true;
    } else if (!anyItemEnabled) {
      state.allEnabled.value = false;
    }
  }

  /// 设置提醒时间
  void setReminderTime(String time) {
    state.reminderTime.value = time;
  }

  /// 保存设置
  Future<void> saveSettings() async {
    try {
      // 将布尔值转换为字符串 "0" 或 "1"
      final result = await DefaultApi().reminderInfoPut<Map<String, dynamic>>(
        isMenstrualPeriod: state.periodReminderEnabled.value ? '1' : '0',
        isOvulationPeriod: state.ovulationReminderEnabled.value ? '1' : '0',
        isPeriodDays: state.ovulationDayReminderEnabled.value ? '1' : '0',
        isOvulationPeriodEnd:
            state.ovulationEndReminderEnabled.value ? '1' : '0',
        reminderTime: state.reminderTime.value,
      );

      if (result != null && result['code'] == 200) {
        Toast.show('保存成功');
      } else {
        Toast.show(result?['msg'] ?? '保存失败');
      }
    } catch (e) {
      Toast.show('保存失败：${e.toString()}');
    }
  }

  /// 从本地存储加载设置
  void loadSettings() {
    // 这里可以从本地存储加载设置
    // final prefs = await SharedPreferences.getInstance();
    // state.allEnabled.value = prefs.getBool('allEnabled') ?? false;
    // state.periodReminderEnabled.value = prefs.getBool('periodReminderEnabled') ?? false;
    // ... 其他设置
  }

  /// 获取启用的提醒类型列表
  List<String> getEnabledReminderTypes() {
    final enabledTypes = <String>[];
    
    if (state.periodReminderEnabled.value) {
      enabledTypes.add('生理期提醒');
    }
    if (state.ovulationReminderEnabled.value) {
      enabledTypes.add('排卵提醒');
    }
    if (state.ovulationDayReminderEnabled.value) {
      enabledTypes.add('排卵日提醒');
    }
    if (state.ovulationEndReminderEnabled.value) {
      enabledTypes.add('排卵结束提醒');
    }
    
    return enabledTypes;
  }

  /// 检查是否有任何提醒启用
  bool hasAnyReminderEnabled() {
    return state.periodReminderEnabled.value ||
           state.ovulationReminderEnabled.value ||
           state.ovulationDayReminderEnabled.value ||
           state.ovulationEndReminderEnabled.value;
  }
}




